import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

const changeListStatus = 'changeListStatus'
const addNote = 'addNote'
const editNote = 'editNote'
const deleteNote = 'deleteNote'
const toggleFavorite = 'toggleFavorite'
const setActiveNote = 'setActiveNote'
const token = 'token'

const state = {
  isAllList: true,
  notes: [],
  activeNote: {},
  token: localStorage.getItem('token'), // 获取token
  iphone: '',
  loadingStatus: false, // loading 动画加载
  alertStatus: false, // 全局提示框
  alertContent: '' // alert提示的内容
}

const mutations = {
  [changeListStatus] (state, bool) {
    state.isAllList = bool
  },
  [addNote] (state) {
    const newNote = {
      text: 'New note',
      favorite: !state.isAllList,
      _rm: Math.random()
    }
    state.notes.push(newNote)
    state.activeNote = newNote
  },
  [editNote] (state, text) {
    state.activeNote.text = text
  },
  [deleteNote] (state) {
    let rm = state.activeNote['_rm']
    let index = state.notes.findIndex(function (v, i) {
      if (rm === v['_rm']) return true
      return false
    })
    if (index >= 0) state.notes.splice(index, 1)
    state.activeNote = state.notes[0] || {}
  },
  [toggleFavorite] (state) {
    state.activeNote['favorite'] = !state.activeNote['favorite']
  },
  [setActiveNote] (state, note) {
    state.activeNote = note
  },
  [token] (state, value) {
    state.token = value
    localStorage.setItem('token', value)
  },
  showLoading (state) {
    state.loadingStatus = true
  },
  hideLoading (state) {
    state.loadingStatus = false
  },
  showAlert (state) {
    state.alertStatus = true
  },
  hideAlert (state) {
    state.alertStatus = false
  },
  changeAlertContent (state, value) {
    state.alertContent = value
    console.log(value)
  }

}

const actions = {
  [changeListStatus] ({commit}, {bool}) {
    commit('changeListStatus', bool)
  },
  [addNote] ({commit}) {
    commit('addNote')
  },
  [editNote] ({commit}, {text}) {
    commit('editNote', text)
  },
  [deleteNote] ({commit}) {
    commit('deleteNote')
  },
  [toggleFavorite] ({commit}) {
    commit('toggleFavorite')
  },
  [setActiveNote] ({commit}, {note}) {
    commit('setActiveNote', note)
  },
  [token] ({commit}) {
    commit('token')
  }
}

const getters = {
  favoriteNotes: state => {
    return state.notes.filter((v, i) => v['favorite'])
  }
}

export default new Vuex.Store({
  state,
  mutations,
  actions,
  getters
})
